package com.example.parallelandroid;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.parallelandroid.entity.Region;

import java.util.ArrayList;
import java.util.List;

public class RegionAdapter extends BaseAdapter {

    private Context mContext;
    private List<Region> regions = new ArrayList<>();
    private int layoutResId;

    public RegionAdapter(Context mContext, List<Region> regions,
                           int layoutResId) {
        this.mContext = mContext;
        this.regions = regions;
        this.layoutResId = layoutResId;
    }

    @Override
    public int getCount() {
        if (regions != null){
            return regions.size();
        }
        return 0;
    }

    @Override
    public Object getItem(int position) {
        if (regions != null){
            return regions.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {//header
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null){
            //加载item的布局文件，生成一个View对象，再给converView赋值
            convertView = LayoutInflater.from(mContext).inflate(layoutResId,null);
            //获取每一个item中的控件对象
            viewHolder = new ViewHolder();
            viewHolder.lvRegion=convertView.findViewById(R.id.lv_region);
            viewHolder.lvPicture=convertView.findViewById(R.id.lv_picture);
//            viewHolder.lvPicture=convertView.findViewById(R.id.lv_picture);
            //将ViewHolder对象同converView关联起来
            convertView.setTag(viewHolder);
        }else {//重复利用convertView对象
            //获取到跟当前的convertView绑定在一起的ViewHolder对象
            viewHolder = (ViewHolder) convertView.getTag();
        }
        viewHolder.lvRegion.setText(regions.get(position).getRegion());
        if(regions.get(position).getRegion().equals("省内")){
            Glide.with(mContext).load(R.drawable.province).into(viewHolder.lvPicture);
        }else{
            Glide.with(mContext).load(R.drawable.china).into(viewHolder.lvPicture);
        }
        //给控件对象绑定要显示的数据
        return convertView;
    }

    private static class ViewHolder{
        //每一个item中的控件
        private TextView lvRegion;
        private ImageView lvPicture;
    }
}
